package com.voute.View.Activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.voute.App.App;
import com.voute.Base.BaseActivity;
import com.voute.Consts.Constants;
import com.voute.Model.Bean.BaseBean;
import com.voute.Model.Bean.PersonInfoBean;
import com.voute.Model.Bean.SimplePushMessageBean;
import com.voute.Model.Bean.UploadImgResponseBean;
import com.voute.Model.Bean.UxTagBean;
import com.voute.Model.IModifyUserInfoModel;
import com.voute.Model.IUploadFileModel;
import com.voute.Model.IUxTagModel;
import com.voute.Model.Impl.ModifyUserInfoModelImpl;
import com.voute.Model.Impl.UXTagModelImpl;
import com.voute.Model.Impl.UploadFileModelImpl;
import com.voute.Presenter.IPersonInfoPresenter;
import com.voute.Presenter.Impl.PersonInfoPresenterImpl;
import com.voute.R;
import com.voute.Utils.CommonSubscriber;
import com.voute.Utils.FileUtils;
import com.voute.Utils.GlideUtils;
import com.voute.Utils.RetrofitUploadFileParameterBuilder;
import com.voute.Utils.TransformUtils;
import com.voute.View.IView.IPersonInfoView;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.RequestBody;
import rx.Observable;
import rx.functions.Func1;

/**
 * 修改个人信息画面
 * Created by liucxu on 2017/1/21.
 */

public class ModifyPersonInfoActivity extends BaseActivity implements IPersonInfoView {

    private CircleImageView profile_image;
    private TextView user_nick_name;
    private TextView user_signature;
    private IPersonInfoPresenter presenter;
    private MaterialDialog progressDialog;
    private RelativeLayout user_nickname_layout;
    private RelativeLayout user_signature_layout;
    private RelativeLayout user_avaster_layout;
    private RelativeLayout back_layout;
    private TextView publish_tv;
    private int REQUEST_CODE_USER_NAME = 0X01;
    private int REQUEST_CODE_USER_SIGNATURE = 0X02;
    private static final int REQUEST_CODE_PICK_IMAGE = 0x03;
    private static final int REQUEST_CODE_TAKE_PHOTO = 0x04;
    private String user_name_string = "";
    private String user_signature_string = "";
    private String user_avaster_string = "";
    private String cature_url = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_modify_person_info;
    }

    @Override
    public void setupView() {
        profile_image = $(R.id.profile_image);
        back_layout=$(R.id.back_layout);
        user_nick_name = $(R.id.user_nick_name);
        user_signature = $(R.id.user_signature);
        user_nickname_layout = $(R.id.user_nickname_layout);
        user_signature_layout = $(R.id.user_signature_layout);
        user_avaster_layout = $(R.id.user_avaster_layout);
        publish_tv = $(R.id.publish_tv);
        publish_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final HashMap<String, String> values = new HashMap<>();
                final IModifyUserInfoModel model = new ModifyUserInfoModelImpl();
                IUxTagModel uxTagModel = new UXTagModelImpl();
                showLoading();
                uxTagModel.getUxTag().flatMap(new Func1<UxTagBean, Observable<BaseBean>>() {
                    @Override
                    public Observable<BaseBean> call(UxTagBean uxTagBean) {
                        values.put("username", user_name_string);
                        values.put("description", user_signature_string);
                        values.put("avatar", user_avaster_string);
                        values.put("uxtag", uxTagBean.getData().getUxtag());
                        return model.modifyUserInfo(values);
                    }
                }).compose(TransformUtils.<BaseBean>defaultSchedulers()).subscribe(new CommonSubscriber<BaseBean>() {
                    @Override
                    public void onSuccess(BaseBean response) {
                        hideLoading();
                        Toast.makeText(ModifyPersonInfoActivity.this, "更新用户数据成功", Toast.LENGTH_SHORT).show();
                        App.GetInstance().finishActivity(ModifyPersonInfoActivity.this);
                    }

                    @Override
                    public void onFailure(BaseBean response) {
                        hideLoading();
                        showError(response.getMsg());
                    }
                });
            }
        });
        back_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                App.GetInstance().finishActivity(ModifyPersonInfoActivity.this);
            }
        });
        presenter = new PersonInfoPresenterImpl(this);
        user_nickname_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ModifyPersonInfoActivity.this, ModifyUserNameSignatureActivity.class);
                intent.putExtra("edit_user_name", true);
                ModifyPersonInfoActivity.this.startActivityForResult(intent, REQUEST_CODE_USER_NAME);
            }
        });

        user_signature_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ModifyPersonInfoActivity.this, ModifyUserNameSignatureActivity.class);
                intent.putExtra("edit_user_name", false);
                intent.putExtra("user_signature",user_signature.getText().toString());
                ModifyPersonInfoActivity.this.startActivityForResult(intent, REQUEST_CODE_USER_SIGNATURE);
            }
        });

        user_avaster_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MaterialDialog.Builder(ModifyPersonInfoActivity.this)
                        .title("选择图片")
                        .items("相册选择", "拍摄照片")
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                if (position == 0) {
                                    Intent intent = new Intent(Intent.ACTION_PICK);
                                    intent.setType("image/*");
                                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                                } else if (position == 1) {
//                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                                    take_photo_uri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + Constants.IMAGE_URL + ((new Date()).getTime())+".jpg");
//                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, take_photo_uri);
//                                    startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
                                    String savePath = "";
                                    // 判断是否挂载了SD卡
                                    String storageState = Environment
                                            .getExternalStorageState();
                                    if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                                        savePath = Environment
                                                .getExternalStorageDirectory()
                                                .getAbsolutePath()
                                                + Constants.IMAGE_URL;// 存放照片的文件夹
                                        File savedir = new File(savePath);
                                        if (!savedir.exists()) {
                                            savedir.mkdirs();
                                        }
                                    } else {
//                                        Toast.makeText(getApplicationContext(), "无法保存照片，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
                                        MaterialDialog notice_dialog = new MaterialDialog.Builder(ModifyPersonInfoActivity.this).title("提示").positiveText("确认").cancelable(false).content("无法保存照片，请检查SD卡是否挂载").build();
                                        notice_dialog.show();
                                        return;
                                    }
                                    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                                    String fileName = "voute_" + timeStamp + ".jpg";// 照片命名
                                    File out = new File(savePath, fileName);
                                    Uri uri = Uri.fromFile(out);
                                    cature_url = savePath + fileName;// 该照片的绝对路径
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                    startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
                                }
                            }
                        })
                        .show();
            }
        });
    }

    @Override
    public void setupData() {
        presenter.getMyInfo();
    }

    @Override
    public void showPersonInfo(PersonInfoBean info) {
        if (TextUtils.isEmpty(info.getData().getUser().getAvatar())) {
            profile_image.setImageResource(R.mipmap.default_avaster);
        } else {
            GlideUtils.getInstance().loadSimpleContextVitMap(this, info.getData().getUser().getAvatar(), profile_image);
            user_avaster_string = info.getData().getUser().getAvatar();
        }
        user_nick_name.setText(info.getData().getUser().getUsername());
        user_name_string = info.getData().getUser().getUsername();
        if (TextUtils.isEmpty(info.getData().getUser().getDescription())) {
            user_signature.setText("这个人很懒什么都没留下");
        } else {
            user_signature.setText(info.getData().getUser().getDescription());
            user_signature_string = info.getData().getUser().getDescription();
        }
    }

    @Override
    public void refreshPushMessages(SimplePushMessageBean msg) {

    }

    @Override
    public void showLoading() {
        if (progressDialog == null) {
            progressDialog = new MaterialDialog.Builder(this)
                    .progress(true, 0)
                    .title("提示")
                    .content("请等待...")
                    .autoDismiss(false)
                    .cancelable(true)
                    .build();
        }
        progressDialog.show();
    }

    @Override
    public void hideLoading() {
        progressDialog.dismiss();
    }

    @Override
    public void showError(String errMsg) {
//        Snackbar.make(profile_image, errMsg, Snackbar.LENGTH_SHORT).show();
        MaterialDialog notice_dialog = new MaterialDialog.Builder(ModifyPersonInfoActivity.this).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void startCropActivity(@NonNull Uri uri) {
        String destinationFileName = ((new Date()).getTime() + "");
        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), destinationFileName + ".jpg")));
        uCrop = ucropConfig(uCrop);
        uCrop.start(ModifyPersonInfoActivity.this);
    }

    private UCrop ucropConfig(@NonNull UCrop uCrop) {
        uCrop = uCrop.withAspectRatio(1, 1);
        UCrop.Options options = new UCrop.Options();
        options.setHideBottomControls(false);
        return uCrop.withOptions(options);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_USER_NAME || requestCode == REQUEST_CODE_USER_SIGNATURE) {
            if (data == null) {
                return;
            } else {
                if (requestCode == REQUEST_CODE_USER_NAME) {
                    String user_name = data.getStringExtra("modify_value");
                    user_nick_name.setText(user_name);
                    user_name_string = user_name;
                } else if (requestCode == REQUEST_CODE_USER_SIGNATURE) {
                    String signature_string = data.getStringExtra("modify_value");
                    user_signature.setText(signature_string);
                    user_signature_string = signature_string;
                }
            }
        }
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            startCropActivity(uri);
        }
        if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
            if (!new File(cature_url).exists()) {
                return;
            }
            startCropActivity(Uri.fromFile(new File(cature_url)));
        }
        if (requestCode == UCrop.REQUEST_CROP) {
            showLoading();
            Uri resultUri = UCrop.getOutput(data);
            File uoload_file = FileUtils.getFileByUri(resultUri);
            RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
            Map<String, RequestBody> params = RetrofitUploadFileParameterBuilder.newBuilder()
                    .addParameter("ftype", "avatar")
                    .addParameter("wsfile", uoload_file)
                    .bulider();
            IUploadFileModel model = new UploadFileModelImpl();
            model.uploadImage("https://up.5miaoapp.com/job", params).compose(TransformUtils.<UploadImgResponseBean>defaultSchedulers()).subscribe(new CommonSubscriber<UploadImgResponseBean>() {
                @Override
                public void onSuccess(UploadImgResponseBean response) {
                    hideLoading();
                    String pic_url = response.getData().getBaseurl() + "_500.jpg";
                    user_avaster_string = pic_url;
                    GlideUtils.getInstance().loadSimpleContextVitMap(ModifyPersonInfoActivity.this, user_avaster_string, profile_image);
                }

                @Override
                public void onFailure(BaseBean response) {
                    hideLoading();
                    showError(response.getMsg());
                }
            });
        }
    }
}
